#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

function usage() {
  console.log(`用法: node scripts/genAvatar.js <text> [--size <n>] [--shape circle|square] [--seed <seed>]`);
  console.log(`示例: node scripts/genAvatar.js alice --size 128 --shape circle`);
}

function parseArgs(argv) {
  const args = { text: null, size: 128, shape: 'circle', seed: null };
  const a = argv.slice(2);
  if (a.length === 0 || a.includes('--help')) return args;
  args.text = a[0];
  for (let i = 1; i < a.length; i++) {
    const v = a[i];
    if (v === '--size') {
      args.size = parseInt(a[++i], 10) || 128;
    } else if (v === '--shape') {
      const s = a[++i];
      if (s === 'circle' || s === 'square') args.shape = s; else console.warn('shape 仅支持 circle|square');
    } else if (v === '--seed') {
      args.seed = a[++i];
    }
  }
  return args;
}

function getInitials(text) {
  const t = (text || '').trim();
  if (!t) return '?';
  const parts = t.split(/\s+|_|-/).filter(Boolean);
  if (parts.length >= 2) {
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  }
  return t.slice(0, 2).toUpperCase();
}

function hslToRgb(h, s, l) {
  s /= 100; l /= 100;
  const k = n => (n + h / 30) % 12;
  const a = s * Math.min(l, 1 - l);
  const f = n => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
  return [Math.round(255 * f(0)), Math.round(255 * f(8)), Math.round(255 * f(4))];
}

function getContrastColor([r, g, b]) {
  // WCAG 相对亮度
  const srgb = [r, g, b].map(v => {
    v /= 255;
    return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
  });
  const L = 0.2126 * srgb[0] + 0.7152 * srgb[1] + 0.0722 * srgb[2];
  return L > 0.5 ? '#000' : '#fff';
}

function pickColor(text, seed) {
  const h = crypto.createHash('sha256').update(seed || text).digest('hex');
  const H = Math.floor(parseInt(h.slice(0, 2), 16) / 255 * 360); // 0..360
  const S = 60 + (parseInt(h.slice(2, 4), 16) % 30); // 60..89
  const L = 50 + (parseInt(h.slice(4, 6), 16) % 10) - 5; // 45..55
  const rgb = hslToRgb(H, S, L);
  const textColor = getContrastColor(rgb);
  return { bgHsl: `hsl(${H}, ${S}%, ${L}%)`, textColor };
}

function buildSvg({ text, size = 128, shape = 'circle', seed }) {
  const initials = getInitials(text);
  const { bgHsl, textColor } = pickColor(text, seed);
  const fontSize = Math.floor(size * 0.5);
  const radius = Math.floor(size / 2);

  const shapeEl = shape === 'circle'
    ? `<circle cx="${radius}" cy="${radius}" r="${radius}" fill="${bgHsl}"/>`
    : `<rect x="0" y="0" width="${size}" height="${size}" rx="${Math.floor(size * 0.18)}" fill="${bgHsl}"/>`;

  return `<?xml version="1.0" encoding="UTF-8"?>\n` +
    `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">\n` +
    `  ${shapeEl}\n` +
    `  <text x="50%" y="50%" fill="${textColor}" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial" font-size="${fontSize}" font-weight="700" text-anchor="middle" dominant-baseline="central">${initials}</text>\n` +
    `</svg>\n`;
}

async function main() {
  const args = parseArgs(process.argv);
  if (!args.text) {
    usage();
    process.exit(1);
  }

  const svg = buildSvg(args);
  const uploadsDir = path.join(__dirname, '..', 'uploads');
  if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
  const fname = `avatar-${Date.now()}-${crypto.randomInt(0, 1e9)}.svg`;
  const fpath = path.join(uploadsDir, fname);
  fs.writeFileSync(fpath, svg, 'utf8');

  const url = `/uploads/${fname}`;
  console.log(JSON.stringify({
    message: '生成成功',
    text: args.text,
    size: args.size,
    shape: args.shape,
    url,
    path: fpath
  }, null, 2));
}

main();